package com.wuyangnju.lj.callcenter.model.server;

import java.util.Collection;
import java.util.LinkedList;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.wuyangnju.lj.callcenter.model.customer.Customer;

public class Server {
	private static final Log log = LogFactory.getLog(Server.class);

	private int limit;
	private AcceptCustomer policy;
	private Collection<Customer> customers;

	public Server(int limit, AcceptCustomer policy) {
		this.limit = limit;
		this.policy = policy;
		customers = new LinkedList<Customer>();
	}

	/**
	 * @return if false, server is full and not available to customer
	 */
	public boolean serve(Customer customer) {
		if (customers.size() < limit) {
			customers.add(customer);
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @return , a customer expected to be in server is missing!
	 */
	public boolean depart(Customer customer) {
		if (customers.contains(customer)) {
			customers.remove(customer);
			return true;
		} else {
			log.error("a customer expected to be in server is missing!");
			return false;
		}
	}

	public Customer acceptCustomer() {
		return policy.acceptCustomer();
	}

	public int size() {
		return customers.size();
	}

	public int sizeFromBuffer(int bufferId) {
		int count = 0;
		for (Customer customer : customers) {
			if (customer.fromBuffer == bufferId) {
				count++;
			}
		}
		return count;
	}
}
